<?php

namespace app\admin\model\goods;

use Monolog\Handler\IFTTTHandler;
use think\Db;
use think\Model;


class Goods extends Model
{

    // 表名
    protected $name = 'goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'attribute_text',
        'freight_text',
        'is_match_text',
        'status_text',
        'create_time_text',
        'update_time_text',
        'spec_type_text',
        'is_new_text',
        'is_hot_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            save($row, 'insert');
        });
        self::beforeUpdate(function ($row) {
            save($row, 'update');
        });
        function save($row, $method){

            if (isset($row['spec_type']) && $row['spec_type'] == 1 && !empty($row['goods_sku'])) {

                $json = json_decode($row['goods_sku'], true);

                    $update = [];
                    $insert = [];
                    $stock = 0;
                    $sales = 0;

                if ($json){
                    foreach ($json as $v) {

                        $v['goods_id'] = $row['id'];
                        $v['spec_value_str'] = $v['spec_value_str'];
                        $v['ordinaryprice'] =  $method == 'update' ? floatval($v['ordinaryprice']) : floatval($v['price']);
                        $v['haveprice']     = floatval($v['haveprice']);
                        $v['agentprice']    = floatval($v['agentprice']);
//                        $v['stock']         = intval($v['stock']);
//                        $v['sales']         = intval($v['sales']);
//                        $stock += $v['stock'];
//                        $sales += $v['sales'];

                        if (empty($v['id'])) {
                            Db::name('goods_item')->where('goods_id',$row['id'])->delete();
                            unset($v['id']);
                            unset($v['spec_name']);
                            unset($v['price']);
                            $insert[] = $v;
                        } else {
                            unset($v['spec_name']);
                            unset($v['price']);
                            $update[] = $v;
                        }
                    }
                }




                if ($update) {
                    $sku = new GoodsItem();
                    $u_ids = array_column($update, 'id', 'id');

                    $sku->where('goods_id', $row['id'])
                        ->where('id', 'not in', $u_ids)->delete();
                    $sku->isUpdate(true)->saveAll($update);
                }

                if ($insert) {

                    Db::name('goods_item')->insertAll($insert);
                }
                if ($method == 'insert') {
                    $row->getQuery()->where('id', $row['id'])->update(['stock' => $stock, 'sales' => $sales]);
                } else {
                    $row->stock = $stock;
                    $row->sales = $sales;
                }
            }else {
                GoodsItem::where('goods_id', $row['id'])->delete();
            }
        }
    }

    
    public function getAttributeList()
    {
        return ['new' => __('Attribute new'), 'second' => __('Attribute second')];
    }

    public function getFreightList()
    {
        return ['0' => __('Freight 0'), '2' => __('Freight 2')];
    }

    public function getIsMatchList()
    {
        return ['0' => __('Is_match 0'), '1' => __('Is_match 1')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }

    public function getSpecTypeList()
    {
        return ['1' => __('Spec_type 1'), '0' => __('Spec_type 0')];
    }

    public function getIsNewList()
    {
        return ['1' => __('Is_new 1'), '0' => __('Is_new 0')];
    }

    public function getIsHotList()
    {
        return ['0' => __('Is_hot 0'), '1' => __('Is_hot 1')];
    }


    public function getAttributeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['attribute']) ? $data['attribute'] : '');
        $list = $this->getAttributeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getFreightTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['freight']) ? $data['freight'] : '');
        $list = $this->getFreightList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsMatchTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_match']) ? $data['is_match'] : '');
        $list = $this->getIsMatchList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getSpecTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['spec_type']) ? $data['spec_type'] : '');
        $list = $this->getSpecTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsNewTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_new']) ? $data['is_new'] : '');
        $list = $this->getIsNewList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsHotTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_hot']) ? $data['is_hot'] : '');
        $list = $this->getIsHotList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function en()
    {
        return $this->belongsTo('app\admin\model\goods\Brand','brand_id','id',[],'LEFT')->setEagerlyType(0);
    }

    public function sku()
    {
        return $this->hasMany('GoodsItem', 'goods_id', 'id');
    }

    /**
     * @param $gid 商品id
     * @param array $data 商品数据
     */
    public function category($gid, $data = [], $type = 0)
    {

        if ($type == 1)
        {
            Db::name('goods_addcategory')->where('gid',$gid)->delete();
        }
        $category_id = explode(',',$data['category_id']);
        $models_id = explode(',',$data['models_id']);
        foreach($category_id as $key => $val)
        {
            foreach($models_id as $models_idk => $models_idv)
            {
                Db::name('goods_addcategory')->insertGetId([
                    'gid' => $gid,
                    'category_id' => $val,
                    'vehicle_id'  => empty($models_idv) ? 0 : $models_idv,
                    'status'      => 0
                ]);
            }
        }

        if ($data['category_status'] == 1)
        {

            $category_ids = explode(',',$data['category_ids']);
            $models_ids   = explode(',',$data['models_ids']);

            foreach($category_ids as $modelsskey => $modelssval)
            {
                foreach($models_ids as $modelsk => $modelsv)
                {
                    Db::name('goods_addcategory')->insertGetId([
                        'gid' => $gid,
                        'category_id' => $modelssval,
                        'vehicle_id'  => empty($models_ids) ? 0 : $modelsv,
                        'status'      => 1
                    ]);
                }
            }
        }
        return true;
    }

}
